@echo off
setlocal

:: 设置变量
set DB_HOST=127.0.0.1
set DB_USER=guangxian
set DB_PASSWORD=admin888
set DB_NAME=guangxian
set BACKUP_DIR=D:\guanxian\houtai\backup
set INFO_TABLE=device_temperatureinfo
set WARING_TABLE=device_warningdeviceinfo

:: 使用 PowerShell 获取标准化日期格式
for /f "delims=" %%A in ('powershell -command "Get-Date -Format yyyy-MM-dd"') do set DATESTAMP=%%A

:: 创建备份目录（如果不存在）
if not exist "%BACKUP_DIR%" mkdir "%BACKUP_DIR%"

:: 备份数据表
mysqldump -h %DB_HOST% -u %DB_USER% -p%DB_PASSWORD% %DB_NAME% %INFO_TABLE% > "%BACKUP_DIR%\%INFO_TABLE%_%DATESTAMP%.sql"
if %errorlevel% neq 0 (
    echo Backup failed.
    exit /b %errorlevel%
)

:: 备份告警表
mysqldump -h %DB_HOST% -u %DB_USER% -p%DB_PASSWORD% %DB_NAME% %WARING_TABLE% > "%BACKUP_DIR%\%WARING_TABLE%_%DATESTAMP%.sql"
if %errorlevel% neq 0 (
    echo Backup failed.
    exit /b %errorlevel%
)

:: 清空数据表
mysql -h %DB_HOST% -u %DB_USER% -p%DB_PASSWORD% -e "USE %DB_NAME%; TRUNCATE TABLE %INFO_TABLE%;"
if %errorlevel% neq 0 (
    echo Truncate failed.
    exit /b %errorlevel%
)

:: 清空告警表
mysql -h %DB_HOST% -u %DB_USER% -p%DB_PASSWORD% -e "USE %DB_NAME%; TRUNCATE TABLE %WARING_TABLE%;"
if %errorlevel% neq 0 (
    echo Truncate failed.
    exit /b %errorlevel%
)

echo Backup and truncate completed successfully.
endlocal